package com.example.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    WebSecurityConfig
 * Author:      AmbroseCdMeng
 * Date:        2021/2/24 15:11
 * Description: 安全配置
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@Configuration
// 指定为 Spring Security 配置类。集成了 Spring Security 的 Web 安全支持
@EnableWebSecurity
// 在配置类的同时集成了 WebSecurityConfigurerAdapter，重写其特定方法，用于自定义 Spring Security 配置，Spring Security 的工作量都集中在该配置类
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 定义了应该被拦截的 URL
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/welcome", "/login").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .and()
                .logout()
                .permitAll();
    }

    // 在内存中配置一个用户，这个用户拥有 User 角色。  admin/123456
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(
                new BCryptPasswordEncoder() // 指定编码方式
        )
                .withUser("admin")
                .password("$2a$10$Q21imUyxDeshQ2tQBUfJKuBHbmuyTsZYoCMRmGi5UcOIavevauZwS")
                .roles("USER");
    }
}
